import React, {
  useState,
  useEffect,
  useRef,
} from "react";
import {
  Card,
  List,
  Input,
  Button,
  Avatar,
  Badge,
  Modal,
  Select,
  message,
  Divider,
  Tooltip,
  Tag,
  Spin,
  Empty,
  Space,
  Dropdown,
  Menu,
  Typography,
} from "antd";
import {
  SendOutlined,
  SearchOutlined,
  RobotOutlined,
  UserOutlined,
  MessageOutlined,
  MoreOutlined,
  DeleteOutlined,
  SettingOutlined,
  ReloadOutlined,
  WifiOutlined,
  BellOutlined,
  CloseOutlined,
  PlusOutlined,
  EditOutlined,
} from "@ant-design/icons";
import { messageApi } from "../../services/messageService";
import { useUser } from "../../contexts/UserContext";
import {
  useWebSocket,
  ConnectionStatus,
} from "../../contexts/WebSocketContext";
import type { User } from "../../contexts/UserContext";
import moment from "moment";
import "./MessageCenter.less";
import UserProfile from "../../components/UserProfile";
import { Navigate } from "react-router-dom";

const { Search } = Input;
const { TextArea } = Input;
const { Option } = Select;
const { Text, Title } = Typography;

// 根据用户角色生成默认头像（与个人资料保持一致）
const getDefaultAvatar = (name: string, role: string) => {
  // 使用姓名的hash值作为种子，避免中文编码问题
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  // 根据角色设置不同的卡通头像样式
  let avatarUrl;
  if (role === "teacher") {
    // 教师使用更成熟的卡通风格
    avatarUrl = `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else if (role === "admin") {
    // 管理员使用权威的卡通风格
    avatarUrl = `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=ffcdd2`;
  } else {
    // 学生使用活泼的卡通风格
    avatarUrl = `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
  
  console.log(`生成头像: ${name} (${role}) -> ${avatarUrl}`);
  return avatarUrl;
};

interface Message {
  id: number;
  fromUserId: number;
  toUserId: number;
  content: string;
  contentType: string;
  createTime: string;
  isRead: number;
  aiSuggestion?: string;
  fromUserInfo?: User;
}

interface Conversation {
  id: string;
  type: string;
  title?: string;
  avatar?: string;
  lastMessage?: Message;
  lastMessageTime?: string;
  unreadCount?: number;
  participants?: number[];
  otherUserId?: number;
  online?: boolean; // Added for online status
}

// 生成丰富的假数据
const generateMockData = (userRole: string) => {
  const studentNames = [
    "李明轩", "王雨涵", "张浩然", "刘雅琪", "陈思远", "杨梦瑶", "赵天宇", "孙诗涵", "周博文", "吴欣怡",
    "徐子轩", "朱雨桐", "胡志强", "郭雅婷", "何俊杰", "马晓雯", "韩志豪", "郑雅文", "冯浩然", "曹梦琪",
    "彭志强", "董雅涵", "袁博文", "潘雨桐", "田志豪", "姜雅文", "魏浩然", "蒋梦琪", "韦志强", "傅雅涵"
  ];

  const teacherNames = [
    "张教授", "李副教授", "王教授", "刘教授", "陈教授", "赵教授", "孙教授", "周教授", "吴教授", "郑教授",
    "钱教授", "孙副教授", "周副教授", "吴副教授", "郑副教授", "王副教授", "李副教授", "赵副教授", "陈副教授", "刘副教授"
  ];

  const adminNames = [
    "管理员小王", "系统管理员", "教务管理员", "技术管理员", "课程管理员", "学生管理员", "教师管理员", "数据管理员", "网络管理员", "安全管理员"
  ];

  const studentMessages = [
    "老师，关于作业的问题我想请教一下",
    "好的，我会按时提交作业",
    "请问这门课的考试时间是什么时候？",
    "老师，我对这个知识点还不太理解",
    "作业已经提交了，请查收",
    "谢谢老师的耐心解答",
    "请问下次课的内容是什么？",
    "老师，我想申请延期提交作业",
    "这个实验报告怎么写比较好？",
    "老师，我想参加您的科研项目"
  ];

  const teacherMessages = [
    "请查看最新的课程安排",
    "作业批改已完成，请查看反馈",
    "下节课我们将学习新的内容",
    "请及时提交实验报告",
    "考试时间已经确定，请关注通知",
    "有同学对课程有疑问吗？",
    "请参加明天的答疑时间",
    "课程资料已更新，请下载",
    "请按时参加实验课",
    "有任何问题都可以随时联系我"
  ];

  const adminMessages = [
    "系统维护通知：今晚22:00-24:00",
    "请及时更新个人信息",
    "新的教学政策已发布",
    "请查看最新的教务通知",
    "系统升级完成，功能已优化",
    "请及时处理待办事项",
    "新的课程安排已发布",
    "请关注系统安全提醒",
    "数据备份已完成",
    "请及时反馈系统使用问题"
  ];

  const groupMessages = [
    "大家好，我是新来的同学",
    "有人知道作业的截止时间吗？",
    "这个知识点有人能解释一下吗？",
    "谢谢大家的帮助",
    "有人想一起组队做项目吗？",
    "分享一个学习资源给大家",
    "有人参加明天的活动吗？",
    "这个实验有人遇到问题吗？",
    "大家觉得这门课怎么样？",
    "有人想一起复习吗？"
  ];

  const conversations: Conversation[] = [];
  const messages: { [key: string]: Message[] } = {};

  // 根据用户角色生成不同的会话
  if (userRole === "student") {
    // 学生：与教师、其他学生、管理员的对话
    for (let i = 1; i <= 25; i++) {
      const isTeacher = i <= 10;
      const isAdmin = i > 10 && i <= 15;
      const isStudent = i > 15;
      
      let title, messagesList, avatarSeed;
      
      if (isTeacher) {
        title = teacherNames[i - 1];
        messagesList = teacherMessages;
        avatarSeed = title;
      } else if (isAdmin) {
        title = adminNames[i - 11];
        messagesList = adminMessages;
        avatarSeed = title;
      } else {
        title = studentNames[i - 16];
        messagesList = studentMessages;
        avatarSeed = title;
      }

      const conversationId = `conv_${i}`;
      const unreadCount = Math.floor(Math.random() * 5);
      const lastMessageIndex = Math.floor(Math.random() * messagesList.length);
      const lastMessageTime = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN');

      conversations.push({
        id: conversationId,
    type: "private",
        title,
        avatar: getDefaultAvatar(title, isTeacher ? "teacher" : isAdmin ? "admin" : "student"),
    lastMessage: {
          id: i * 100,
          fromUserId: i + 1,
      toUserId: 1,
          content: messagesList[lastMessageIndex],
      contentType: "text",
          createTime: lastMessageTime,
          isRead: unreadCount === 0 ? 1 : 0,
        },
        lastMessageTime,
        unreadCount,
        participants: [1, i + 1],
        otherUserId: i + 1,
        online: Math.random() > 0.5, // Random online status
      });

      // 生成对话消息
      const conversationMessages: Message[] = [];
      const messageCount = Math.floor(Math.random() * 20) + 5;
      
      for (let j = 0; j < messageCount; j++) {
        const isFromOther = j % 2 === 0;
        const messageIndex = Math.floor(Math.random() * messagesList.length);
        const messageTime = new Date(Date.now() - (messageCount - j) * 60 * 60 * 1000).toLocaleString('zh-CN');
        
        conversationMessages.push({
          id: i * 100 + j,
          fromUserId: isFromOther ? i + 1 : 1,
          toUserId: isFromOther ? 1 : i + 1,
          content: messagesList[messageIndex],
      contentType: "text",
          createTime: messageTime,
      isRead: 1,
        });
      }
      
      messages[conversationId] = conversationMessages;
    }
  } else if (userRole === "teacher") {
    // 教师：与学生、其他教师、管理员的对话
    for (let i = 1; i <= 30; i++) {
      const isStudent = i <= 15;
      const isTeacher = i > 15 && i <= 25;
      const isAdmin = i > 25;
      
      let title, messagesList, avatarSeed;
      
      if (isStudent) {
        title = studentNames[i - 1];
        messagesList = studentMessages;
        avatarSeed = title;
      } else if (isTeacher) {
        title = teacherNames[i - 16];
        messagesList = teacherMessages;
        avatarSeed = title;
      } else {
        title = adminNames[i - 26];
        messagesList = adminMessages;
        avatarSeed = title;
      }

      const conversationId = `conv_${i}`;
      const unreadCount = Math.floor(Math.random() * 5);
      const lastMessageIndex = Math.floor(Math.random() * messagesList.length);
      const lastMessageTime = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN');

      conversations.push({
        id: conversationId,
    type: "private",
        title,
        avatar: getDefaultAvatar(title, isTeacher ? "teacher" : isAdmin ? "admin" : "student"),
    lastMessage: {
          id: i * 100,
          fromUserId: i + 1,
          toUserId: 1,
          content: messagesList[lastMessageIndex],
      contentType: "text",
          createTime: lastMessageTime,
          isRead: unreadCount === 0 ? 1 : 0,
        },
        lastMessageTime,
        unreadCount,
        participants: [1, i + 1],
        otherUserId: i + 1,
        online: Math.random() > 0.5, // Random online status
      });

      // 生成对话消息
      const conversationMessages: Message[] = [];
      const messageCount = Math.floor(Math.random() * 20) + 5;
      
      for (let j = 0; j < messageCount; j++) {
        const isFromOther = j % 2 === 0;
        const messageIndex = Math.floor(Math.random() * messagesList.length);
        const messageTime = new Date(Date.now() - (messageCount - j) * 60 * 60 * 1000).toLocaleString('zh-CN');
        
        conversationMessages.push({
          id: i * 100 + j,
          fromUserId: isFromOther ? i + 1 : 1,
          toUserId: isFromOther ? 1 : i + 1,
          content: messagesList[messageIndex],
      contentType: "text",
          createTime: messageTime,
      isRead: 1,
        });
      }
      
      messages[conversationId] = conversationMessages;
    }
  } else {
    // 管理员：与所有用户的对话
    for (let i = 1; i <= 35; i++) {
      const isStudent = i <= 20;
      const isTeacher = i > 20 && i <= 30;
      const isAdmin = i > 30;
      
      let title, messagesList, avatarSeed;
      
      if (isStudent) {
        title = studentNames[i - 1];
        messagesList = studentMessages;
        avatarSeed = title;
      } else if (isTeacher) {
        title = teacherNames[i - 21];
        messagesList = teacherMessages;
        avatarSeed = title;
      } else {
        title = adminNames[i - 31];
        messagesList = adminMessages;
        avatarSeed = title;
      }

      const conversationId = `conv_${i}`;
      const unreadCount = Math.floor(Math.random() * 5);
      const lastMessageIndex = Math.floor(Math.random() * messagesList.length);
      const lastMessageTime = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN');

      conversations.push({
        id: conversationId,
        type: "private",
        title,
        avatar: getDefaultAvatar(title, isTeacher ? "teacher" : isAdmin ? "admin" : "student"),
        lastMessage: {
          id: i * 100,
          fromUserId: i + 1,
      toUserId: 1,
          content: messagesList[lastMessageIndex],
      contentType: "text",
          createTime: lastMessageTime,
          isRead: unreadCount === 0 ? 1 : 0,
        },
        lastMessageTime,
        unreadCount,
        participants: [1, i + 1],
        otherUserId: i + 1,
        online: Math.random() > 0.5, // Random online status
      });

      // 生成对话消息
      const conversationMessages: Message[] = [];
      const messageCount = Math.floor(Math.random() * 20) + 5;
      
      for (let j = 0; j < messageCount; j++) {
        const isFromOther = j % 2 === 0;
        const messageIndex = Math.floor(Math.random() * messagesList.length);
        const messageTime = new Date(Date.now() - (messageCount - j) * 60 * 60 * 1000).toLocaleString('zh-CN');
        
        conversationMessages.push({
          id: i * 100 + j,
          fromUserId: isFromOther ? i + 1 : 1,
          toUserId: isFromOther ? 1 : i + 1,
          content: messagesList[messageIndex],
      contentType: "text",
          createTime: messageTime,
      isRead: 1,
        });
      }
      
      messages[conversationId] = conversationMessages;
    }
  }

  return { conversations, messages };
};

// 错误边界组件
class ErrorBoundary extends React.Component<any, { hasError: boolean; error: any }> {
  constructor(props: any) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: any) {
    return { hasError: true, error };
  }

  componentDidCatch(error: any, errorInfo: any) {
    console.error("MessageCenter Error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
          <div style={{ 
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100vh',
          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
          color: 'white',
          textAlign: 'center',
          padding: '40px'
        }}>
          <div style={{ fontSize: '48px', marginBottom: '20px' }}>⚠️</div>
          <h2 style={{ marginBottom: '16px', fontSize: '24px' }}>消息中心出现错误</h2>
          <p style={{ marginBottom: '24px', opacity: 0.8 }}>
            抱歉，消息中心遇到了问题。请刷新页面重试。
          </p>
          <Button
            type="primary"
            size="large"
              onClick={() => window.location.reload()} 
              style={{
              background: 'rgba(255, 255, 255, 0.2)',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              borderRadius: '12px',
              height: '48px',
              padding: '0 32px',
              fontSize: '16px',
              fontWeight: 600
              }}
            >
              刷新页面
          </Button>
          <details style={{ marginTop: '24px', opacity: 0.7, textAlign: 'left' }}>
            <summary style={{ cursor: 'pointer', marginBottom: '8px' }}>错误详情</summary>
            <pre style={{ 
              background: 'rgba(0, 0, 0, 0.2)', 
              padding: '12px', 
              borderRadius: '8px',
              fontSize: '12px',
              maxWidth: '500px',
              overflow: 'auto'
            }}>
              {this.state.error?.toString()}
            </pre>
          </details>
        </div>
      );
    }

    return this.props.children;
  }
}

const MessageCenter: React.FC = () => {
  const { user: authUser } = useUser();
  const { state: wsState, sendMessage: sendWsMessage } = useWebSocket();
  
  // 确保当前用户有头像，如果没有则使用默认头像
  const user = authUser ? {
    ...authUser,
    avatar: authUser.avatar || getDefaultAvatar(authUser.name || "当前用户", authUser.role || "teacher")
  } : {
    id: "1",
    name: "当前用户",
    role: "teacher" as const,
    email: "user@example.com",
    avatar: getDefaultAvatar("当前用户", "teacher"),
    permissions: []
  };

  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [newMessage, setNewMessage] = useState("");
  const [searchKeyword, setSearchKeyword] = useState("");
  const [showProfile, setShowProfile] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [showChatModal, setShowChatModal] = useState(false);
  const [chatModalUser, setChatModalUser] = useState<User | null>(null);
  const [showHistoryModal, setShowHistoryModal] = useState(false);
  const [historyConversation, setHistoryConversation] = useState<Conversation | null>(null);
  const [replyToMessage, setReplyToMessage] = useState<Message | null>(null);
  const [replyContent, setReplyContent] = useState("");
  const [chatMessage, setChatMessage] = useState("");
  const [aiSuggestionLoading, setAiSuggestionLoading] = useState(false);
  const [showNewConversationModal, setShowNewConversationModal] = useState(false);
  const [frequentContacts, setFrequentContacts] = useState<User[]>([]);
  const [searchContactKeyword, setSearchContactKeyword] = useState("");
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const chatMessagesEndRef = useRef<HTMLDivElement>(null);

  // WebSocket 连接状态处理
  useEffect(() => {
    if (wsState.messageStatus === "connected") {
      console.log("WebSocket connected for MessageCenter");
      
    const handleNewMessage = (event: CustomEvent) => {
        const newMessage = event.detail;
        console.log("Received new message:", newMessage);
        
        // 更新对话列表中的最后消息
        setConversations(prev => 
          prev.map(conv => 
            conv.id === newMessage.conversationId 
              ? { 
                  ...conv, 
                  lastMessage: newMessage,
                  lastMessageTime: newMessage.createTime,
                  unreadCount: (conv.unreadCount || 0) + 1
                }
              : conv
          )
        );
        
        // 如果当前正在查看这个对话，更新消息列表
        if (selectedConversation?.id === newMessage.conversationId) {
          setMessages(prev => [...prev, newMessage]);
        }
      };

    const handleError = (error: ErrorEvent) => {
        console.error("WebSocket error in MessageCenter:", error);
        // 静默处理错误，不显示错误消息
        // message.error("消息连接出现问题，请检查网络");
      };

      window.addEventListener('newMessage', handleNewMessage as EventListener);
      window.addEventListener('websocketError', handleError as EventListener);

    return () => {
        window.removeEventListener('newMessage', handleNewMessage as EventListener);
        window.removeEventListener('websocketError', handleError as EventListener);
      };
    }
  }, [wsState.messageStatus, selectedConversation]);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const scrollChatToBottom = () => {
    chatMessagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  // 加载对话列表
  const loadConversations = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      const { conversations: mockConversations } = generateMockData(user?.role || "student");
      setConversations(mockConversations);
    } catch (error) {
      console.error("加载对话列表失败:", error);
      // 静默处理错误，不显示错误消息
    } finally {
      setLoading(false);
    }
  };

  // 加载未读消息数
  const loadUnreadCount = async () => {
    try {
      // 使用mock数据替代API调用，避免网络错误
      const mockUnreadCount = {
        total: conversations.reduce((total, conv) => total + (conv.unreadCount || 0), 0),
        conversations: conversations.map(conv => ({
          conversationId: conv.id,
          unreadCount: conv.unreadCount || 0
        }))
      };
      console.log("未读消息数:", mockUnreadCount);
      return mockUnreadCount;
    } catch (error) {
      console.error("加载未读消息数失败:", error);
      return { total: 0, conversations: [] };
    }
  };

  // 计算总未读消息数
  const totalUnreadCount = conversations.reduce((total, conv) => total + (conv.unreadCount || 0), 0);

  // 生成常用联系人列表
  const generateFrequentContacts = () => {
    const studentNames = [
      "李明轩", "王雨涵", "张浩然", "刘雅琪", "陈思远", "杨梦瑶", "赵天宇", "孙诗涵", "周博文", "吴欣怡",
      "徐子轩", "朱雨桐", "胡志强", "郭雅婷", "何俊杰", "马晓雯", "韩志豪", "郑雅文", "冯浩然", "曹梦琪"
    ];

    const teacherNames = [
      "张教授", "李副教授", "王教授", "刘教授", "陈教授", "赵教授", "孙教授", "周教授", "吴教授", "郑教授"
    ];

    const adminNames = [
      "管理员小王", "系统管理员", "教务管理员", "技术管理员", "课程管理员"
    ];

    const contacts: User[] = [];

    // 根据用户角色生成不同的常用联系人
    if (user?.role === "student") {
      // 学生：主要与教师和管理员联系
      teacherNames.slice(0, 8).forEach((name, index) => {
        contacts.push({
          id: String(index + 1),
          name,
          avatar: getDefaultAvatar(name, "teacher"),
          role: "teacher",
          email: `${name}@university.edu.cn`,
          permissions: []
        });
      });

      adminNames.slice(0, 3).forEach((name, index) => {
        contacts.push({
          id: String(index + 100),
          name,
          avatar: getDefaultAvatar(name, "admin"),
          role: "admin",
          email: `${name}@university.edu.cn`,
          permissions: []
        });
      });

      // 添加几个同学
      studentNames.slice(0, 4).forEach((name, index) => {
        contacts.push({
          id: String(index + 200),
          name,
          avatar: getDefaultAvatar(name, "student"),
          role: "student",
          email: `${name}@student.university.edu.cn`,
          permissions: []
        });
      });
    } else if (user?.role === "teacher") {
      // 教师：主要与学生和其他教师联系
      studentNames.slice(0, 10).forEach((name, index) => {
        contacts.push({
          id: String(index + 1),
          name,
          avatar: getDefaultAvatar(name, "student"),
          role: "student",
          email: `${name}@student.university.edu.cn`,
          permissions: []
        });
      });

      teacherNames.slice(0, 5).forEach((name, index) => {
        contacts.push({
          id: String(index + 100),
          name,
          avatar: getDefaultAvatar(name, "teacher"),
          role: "teacher",
          email: `${name}@university.edu.cn`,
          permissions: []
        });
      });

      adminNames.slice(0, 3).forEach((name, index) => {
        contacts.push({
          id: String(index + 200),
          name,
          avatar: getDefaultAvatar(name, "admin"),
          role: "admin",
          email: `${name}@university.edu.cn`,
          permissions: []
        });
      });
    } else {
      // 管理员：与所有用户联系
      studentNames.slice(0, 8).forEach((name, index) => {
        contacts.push({
          id: String(index + 1),
          name,
          avatar: getDefaultAvatar(name, "student"),
          role: "student",
          email: `${name}@student.university.edu.cn`,
          permissions: []
        });
      });

      teacherNames.slice(0, 6).forEach((name, index) => {
        contacts.push({
          id: String(index + 100),
          name,
          avatar: getDefaultAvatar(name, "teacher"),
          role: "teacher",
          email: `${name}@university.edu.cn`,
          permissions: []
        });
      });

      adminNames.slice(0, 4).forEach((name, index) => {
        contacts.push({
          id: String(index + 200),
          name,
          avatar: getDefaultAvatar(name, "admin"),
          role: "admin",
          email: `${name}@university.edu.cn`,
          permissions: []
        });
      });
    }

    return contacts;
  };

  // 标记对话为已读
  const markConversationAsRead = (conversationId: string) => {
    setConversations(prev => 
      prev.map(conv => 
        conv.id === conversationId 
          ? { ...conv, unreadCount: 0 }
          : conv
      )
    );
  };

  // 加载对话消息
  const loadConversationMessages = (conversationId: string) => {
    // 标记对话为已读
    markConversationAsRead(conversationId);
    
    // 模拟加载消息数据
    const mockMessages: Message[] = [
      {
        id: 1,
        fromUserId: Number(user?.id) || 1,
        toUserId: 2,
        content: "你好！请问有什么可以帮助你的吗？",
        contentType: "text",
        createTime: "2025/7/18 09:00:00",
        isRead: 1,
      },
      {
        id: 2,
        fromUserId: 2,
        toUserId: Number(user?.id) || 1,
        content: "老师好！我想问一下关于作业的问题",
        contentType: "text",
        createTime: "2025/7/18 09:02:00",
        isRead: 1,
      },
      {
        id: 3,
        fromUserId: Number(user?.id) || 1,
        toUserId: 2,
        content: "好的，请详细说明一下你的问题",
        contentType: "text",
        createTime: "2025/7/18 09:05:00",
        isRead: 1,
      },
      {
        id: 4,
        fromUserId: 2,
        toUserId: Number(user?.id) || 1,
        content: "是关于第三章的实验报告，我不太理解其中的数据处理部分",
        contentType: "text",
        createTime: "2025/7/18 09:08:00",
        isRead: 1,
      },
      {
        id: 5,
        fromUserId: Number(user?.id) || 1,
        toUserId: 2,
        content: "我明白了，数据处理部分确实比较重要。你可以先看看课本第45页的例题，然后我们再具体讨论",
        contentType: "text",
        createTime: "2025/7/18 09:12:00",
        isRead: 1,
      },
      {
        id: 6,
        fromUserId: 2,
        toUserId: Number(user?.id) || 1,
        content: "好的，我先去看看，谢谢老师！",
        contentType: "text",
        createTime: "2025/7/18 09:15:00",
        isRead: 1,
      },
      {
        id: 7,
        fromUserId: Number(user?.id) || 1,
        toUserId: 2,
        content: "不客气！如果还有问题随时联系我",
        contentType: "text",
        createTime: "2025/7/18 09:18:00",
        isRead: 1,
      },
      {
        id: 8,
        fromUserId: 2,
        toUserId: Number(user?.id) || 1,
        content: "老师，我已经看完了例题，但还是有些地方不太明白",
        contentType: "text",
        createTime: "2025/7/18 10:30:00",
        isRead: 1,
      },
      {
        id: 9,
        fromUserId: Number(user?.id) || 1,
        toUserId: 2,
        content: "具体是哪个步骤不明白呢？你可以把例题的步骤截图发给我看看",
        contentType: "text",
        createTime: "2025/7/18 10:35:00",
        isRead: 1,
      },
      {
        id: 10,
        fromUserId: 2,
        toUserId: Number(user?.id) || 1,
        content: "好的，我马上截图发给你",
        contentType: "text",
        createTime: "2025/7/18 10:40:00",
        isRead: 0,
      }
    ];

    setMessages(mockMessages);
    setTimeout(() => {
      scrollToBottom();
    }, 100);
  };

  // 标记消息为已读
  const markAsRead = async (conversationId: string) => {
    try {
      // 使用模拟数据，实际应该调用API
      setConversations(prev => 
        prev.map(conv => 
          conv.id === conversationId 
            ? { ...conv, unreadCount: 0 }
            : conv
        )
      );
    } catch (error) {
      console.error("标记已读失败:", error);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!newMessage.trim() || !selectedConversation) return;
    
    setSending(true);
    try {
      const messageData = {
        conversationId: selectedConversation.id,
        content: newMessage,
        contentType: "text"
      };
      
      // 发送WebSocket消息
      if (sendWsMessage) {
        sendWsMessage(messageData);
      }
      
      // 添加到本地消息列表
      const newMsg: Message = {
        id: Date.now(),
        fromUserId: Number(user?.id) || 1,
        toUserId: Number(selectedConversation.otherUserId) || 1,
        content: newMessage,
        contentType: "text",
        createTime: new Date().toLocaleString('zh-CN'),
        isRead: 1,
      };
      
      setMessages(prev => [...prev, newMsg]);
      setNewMessage("");

      // 更新对话列表的最后消息
      setConversations(prev => 
        prev.map(conv => 
          conv.id === selectedConversation.id 
            ? { 
                ...conv, 
                lastMessage: newMsg,
                lastMessageTime: newMsg.createTime
              }
            : conv
        )
      );
      
      scrollToBottom();
    } catch (error) {
      console.error("发送消息失败:", error);
      message.error("发送消息失败");
    } finally {
      setSending(false);
    }
  };

  // 搜索用户
  const searchUsers = async (keyword: string) => {
    try {
      // 使用mock数据替代API调用，避免网络错误
      const mockSearchResults = generateFrequentContacts().filter(contact =>
        contact.name.toLowerCase().includes(keyword.toLowerCase()) ||
        contact.email.toLowerCase().includes(keyword.toLowerCase())
      );
      console.log("搜索结果:", mockSearchResults);
      return mockSearchResults;
    } catch (error) {
      console.error("搜索用户失败:", error);
      return [];
    }
  };

  // 开始新对话
  const startChat = async (targetUser: User) => {
    try {
      // 创建新的对话
        const newConversation: Conversation = {
        id: `conv_${Date.now()}`,
          type: "private",
          title: targetUser.name,
          avatar: targetUser.avatar,
        lastMessage: undefined,
        lastMessageTime: new Date().toLocaleString('zh-CN'),
        unreadCount: 0,
        participants: [Number(user?.id) || 1, Number(targetUser.id)],
          otherUserId: Number(targetUser.id),
        online: Math.random() > 0.5, // Random online status
        };

      setConversations(prev => [newConversation, ...prev]);
      setSelectedConversation(newConversation);
        setMessages([]);
      setShowChatModal(false);
      setChatModalUser(null);
    } catch (error) {
      console.error("开始新对话失败:", error);
      message.error("开始新对话失败");
    }
  };

  // 打开新会话模态框
  const openNewConversationModal = () => {
    const contacts = generateFrequentContacts();
    setFrequentContacts(contacts);
    setShowNewConversationModal(true);
    setSearchContactKeyword("");
  };

  // 选择联系人开始聊天
  const selectContactToChat = (contact: User) => {
    setShowNewConversationModal(false);
    setSearchContactKeyword("");
    
    // 检查是否已存在与该用户的对话
    const existingConversation = conversations.find(
      conv => conv.otherUserId === Number(contact.id) || conv.title === contact.name
    );
    
    if (existingConversation) {
      // 如果已存在对话，直接打开该对话
      setSelectedConversation(existingConversation);
      loadConversationMessages(existingConversation.id);
      setShowChatModal(true);
      setChatModalUser(contact);
    } else {
      // 如果不存在，创建新对话
      startChat(contact);
      setShowChatModal(true);
      setChatModalUser(contact);
    }
  };

  // 生成AI建议
  const generateAISuggestion = async (msgId: number) => {
    setAiSuggestionLoading(true);
    try {
      // 使用mock数据替代API调用，避免网络错误
      const mockAISuggestion = {
        suggestion: "这是一个AI生成的建议回复，可以帮助你更好地表达想法。",
        confidence: 0.85,
        alternatives: [
          "另一个建议回复选项1",
          "另一个建议回复选项2"
        ]
      };
      console.log("AI建议:", mockAISuggestion);
      message.success("AI建议已生成");
      return mockAISuggestion;
    } catch (error) {
      console.error("生成AI建议失败:", error);
      return null;
    } finally {
      setAiSuggestionLoading(false);
    }
  };

  // 键盘事件处理
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 渲染消息
  const renderMessage = (msg: Message) => {
    const isOwnMessage = msg.fromUserId === Number(user?.id);
    const messageTime = new Date(msg.createTime).toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });

    return (
      <div
        key={msg.id}
        style={{
          display: 'flex',
          justifyContent: isOwnMessage ? 'flex-end' : 'flex-start',
          marginBottom: '16px',
          padding: '0 20px'
        }}
      >
        <div
          style={{
            maxWidth: '70%',
            display: 'flex',
            flexDirection: isOwnMessage ? 'row-reverse' : 'row',
            alignItems: 'flex-end',
            gap: '8px'
          }}
        >
          {!isOwnMessage && (
            <Avatar
              size={32}
              src={chatModalUser?.avatar || selectedConversation?.avatar}
              icon={<UserOutlined />}
              style={{ flexShrink: 0 }}
            />
          )}
          
          <div
            style={{
              background: isOwnMessage ? '#1890ff' : '#f5f5f5',
              color: isOwnMessage ? 'white' : '#333',
              padding: '12px 16px',
              borderRadius: '18px',
              borderTopLeftRadius: isOwnMessage ? '18px' : '4px',
              borderTopRightRadius: isOwnMessage ? '4px' : '18px',
              wordBreak: 'break-word',
              lineHeight: '1.5',
              position: 'relative',
              maxWidth: '100%'
            }}
              >
                {msg.content}
            
            <div
              style={{
                fontSize: '11px',
                opacity: 0.7,
                marginTop: '4px',
                textAlign: isOwnMessage ? 'right' : 'left'
              }}
            >
              {messageTime}
            </div>
            </div>
          
          {isOwnMessage && (
            <Avatar
              size={32}
              src={user?.avatar}
              icon={<UserOutlined />}
              style={{ flexShrink: 0 }}
            />
          )}
        </div>
      </div>
    );
  };

  // 渲染对话项
  const renderConversationItem = (conversation: Conversation) => {
    const isSelected = selectedConversation?.id === conversation.id;
    const hasUnread = (conversation.unreadCount || 0) > 0;

    return (
      <div
        key={conversation.id}
        onClick={() => {
          setSelectedConversation(conversation);
          loadConversationMessages(conversation.id);
          setShowChatModal(true);
          setChatModalUser({
            id: String(conversation.otherUserId || 1),
            name: conversation.title || "用户",
            avatar: conversation.avatar || "",
            role: "student",
            email: "",
            permissions: []
          });
        }}
        style={{
          display: 'flex',
          alignItems: 'center',
          padding: '16px 20px',
          cursor: 'pointer',
          borderBottom: '1px solid #f0f0f0',
          background: isSelected ? '#f8f9ff' : 'transparent',
          transition: 'all 0.2s ease',
          position: 'relative'
        }}
      >
        <div style={{ position: 'relative', marginRight: '12px' }}>
              <Avatar
            size={48}
                src={conversation.avatar}
            icon={<UserOutlined />}
            style={{
              border: hasUnread ? '2px solid #ff4d4f' : '2px solid transparent'
            }}
          />
          {hasUnread && (
            <Badge
              count={conversation.unreadCount}
              style={{
                position: 'absolute',
                top: '-6px',
                right: '-6px',
                backgroundColor: '#ff4d4f',
                border: '2px solid white'
              }}
            />
          )}
        </div>
        
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
            <Text
              strong
              style={{
                fontSize: '15px',
                color: hasUnread ? '#333' : '#666',
                fontWeight: hasUnread ? 600 : 500,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
              }}
            >
              {conversation.title}
            </Text>
            <Text
              style={{
                fontSize: '12px',
                color: hasUnread ? '#1890ff' : '#999',
                flexShrink: 0,
                marginLeft: '8px'
              }}
            >
              {conversation.lastMessageTime}
            </Text>
            </div>
          
          <Text
            style={{
              fontSize: '13px',
              color: hasUnread ? '#333' : '#999',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              lineHeight: '1.4'
            }}
          >
            {conversation.lastMessage?.content || '暂无消息'}
          </Text>
            </div>
        </div>
    );
  };

  // 打开用户资料
  const openProfile = (user: User) => {
    setSelectedUser(user);
    setShowProfile(true);
  };
  
  // 从资料页面开始聊天
  const handleChatFromProfile = (userId: string) => {
    setShowProfile(false);
    // 查找用户并开始聊天
    const targetUser: User = { 
      id: userId, 
      name: "用户", 
      avatar: "", 
      role: "student",
      email: "",
      permissions: []
    };
    startChat(targetUser);
  };

  // 打开聊天模态框
  const openChatModal = (user: User) => {
    setChatModalUser(user);
    setShowChatModal(true);
  };

  // 打开对话历史模态框
  const openConversationHistoryModal = (conversation: Conversation) => {
    setHistoryConversation(conversation);
    setShowHistoryModal(true);
  };

  // 开始回复
  const startReply = (message: Message) => {
    setReplyToMessage(message);
    setReplyContent("");
  };

  // 取消回复
  const cancelReply = () => {
    setReplyToMessage(null);
    setReplyContent("");
  };

  // 发送回复
  const sendReply = () => {
    if (!replyContent.trim() || !replyToMessage) return;
    
    // 发送回复逻辑
    console.log("发送回复:", replyContent, "回复消息:", replyToMessage);
    
    // 添加到消息列表
    const replyMsg: Message = {
      id: Date.now(),
      fromUserId: Number(user?.id) || 1,
      toUserId: replyToMessage.fromUserId,
      content: `回复 ${replyToMessage.fromUserInfo?.name || '用户'}: ${replyContent}`,
      contentType: "text",
      createTime: new Date().toLocaleString('zh-CN'),
      isRead: 1,
    };
    
    setMessages(prev => [...prev, replyMsg]);
    setReplyContent("");
    setReplyToMessage(null);
    
    scrollToBottom();
  };

  // 回复键盘事件
  const handleReplyKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendReply();
    }
  };

  // 发送聊天模态框消息
  const sendChatMessage = () => {
    if (!chatMessage.trim() || !chatModalUser || !selectedConversation) return;

    // 创建新消息
    const newMsg: Message = {
      id: Date.now(),
      fromUserId: Number(user?.id) || 1,
      toUserId: Number(chatModalUser.id),
      content: chatMessage.trim(),
      contentType: "text",
      createTime: new Date().toLocaleString('zh-CN'),
      isRead: 1,
    };
    
    // 添加到消息列表
    setMessages(prev => [...prev, newMsg]);
    
    // 更新对话列表的最后消息
    setConversations(prev => 
      prev.map(conv => 
        conv.id === selectedConversation.id 
          ? { 
              ...conv, 
              lastMessage: newMsg,
              lastMessageTime: newMsg.createTime
            }
          : conv
      )
    );
    
    setChatMessage("");
    scrollChatToBottom();
    
    // 显示发送成功提示
    message.success("消息已发送");
  };

  // 聊天模态框键盘事件
  const handleChatKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendChatMessage();
    }
  };

  // 初始化加载
  useEffect(() => {
    loadConversations();
    loadUnreadCount();
  }, []);

  // 自动滚动
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    scrollChatToBottom();
  }, [chatMessage]);
  
  if (!user) {
    return <Navigate to="/login" replace />;
  }

  return (
    <div className="modern-message-center">
      {/* 头部 */}
          <div className="message-header">
            <div className="header-left">
          <Title level={2} className="header-title">
                <MessageOutlined />
            消息中心
            {totalUnreadCount > 0 && (
              <Badge
                count={totalUnreadCount}
                className="unread-badge"
              />
            )}
          </Title>
            </div>
        
            <div className="header-actions">
              <Button
                type="primary"
            icon={<PlusOutlined />}
            onClick={openNewConversationModal}
            className="new-conversation-btn"
              >
                发起新会话
              </Button>
          
          <Button
            icon={<ReloadOutlined />}
            onClick={loadConversations}
            loading={loading}
            className="refresh-btn"
          />
            </div>
          </div>

      {/* 主要内容区域 */}
      <div className="message-content">
        {/* 对话列表 */}
        <div className="conversation-list">
          <div className="conversation-header">
            <Search
              placeholder="搜索对话..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="search-input"
            />
                    </div>
          
          <div className="conversation-items">
            {loading ? (
              <div className="loading-container">
                <Spin size="large" />
                <Text>加载对话中...</Text>
                  </div>
            ) : conversations.length === 0 ? (
              <div className="empty-container">
                <Empty
                  description="暂无对话"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
                  </div>
            ) : (
              conversations
                .filter(conv => 
                  conv.title?.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                  conv.lastMessage?.content.toLowerCase().includes(searchKeyword.toLowerCase())
                )
                .map(renderConversationItem)
            )}
          </div>
                </div>

        {/* 右侧空白区域提示 */}
        {!selectedConversation && (
          <div className="empty-message-area">
            <Empty
              description="选择一个对话开始聊天"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
              </div>
            )}
          </div>

      {/* AI助手浮动按钮 */}
      <div className="ai-assistant-fab">
        <Tooltip title="AI助手" placement="left">
                    <Button
                      type="primary"
            shape="circle"
            icon={<RobotOutlined />}
            size="large"
            className="ai-fab-btn"
          />
        </Tooltip>
      </div>

      {/* 用户资料模态框 */}
      <Modal
        title="用户资料"
        open={showProfile}
        onCancel={() => setShowProfile(false)}
        footer={null}
        width={600}
        className="profile-modal"
      >
        {selectedUser && (
          <UserProfile
            user={selectedUser}
            onChat={handleChatFromProfile}
          />
        )}
      </Modal>

      {/* 聊天模态框 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Avatar
              size={32}
              src={chatModalUser?.avatar}
              icon={<UserOutlined />}
            />
            <span>{chatModalUser?.name || '聊天'}</span>
          </div>
        }
        open={showChatModal}
        onCancel={() => {
          setShowChatModal(false);
          setChatModalUser(null);
          setChatMessage("");
        }}
        footer={null}
        width={800}
        className="chat-modal"
        style={{ top: 20 }}
      >
        <div className="chat-modal-content">
          {/* 消息历史区域 */}
          <div className="chat-messages-area">
            {selectedConversation && messages.length > 0 ? (
          <div className="chat-messages">
                {messages.map((msg) => {
                const isOwnMessage = msg.fromUserId === Number(user?.id);
                  const messageTime = new Date(msg.createTime).toLocaleString('zh-CN', {
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                  });

                return (
                  <div
                    key={msg.id}
                      style={{
                        display: 'flex',
                        justifyContent: isOwnMessage ? 'flex-end' : 'flex-start',
                        marginBottom: '16px',
                        padding: '0 16px'
                      }}
                    >
                      <div
                        style={{
                          maxWidth: '70%',
                          display: 'flex',
                          flexDirection: isOwnMessage ? 'row-reverse' : 'row',
                          alignItems: 'flex-end',
                          gap: '8px'
                        }}
                      >
                      {!isOwnMessage && (
                        <Avatar
                            size={32}
                            src={chatModalUser?.avatar}
                          icon={<UserOutlined />}
                            style={{ flexShrink: 0 }}
                          />
                        )}
                        
                        <div
                          style={{
                            background: isOwnMessage ? '#1890ff' : '#f5f5f5',
                            color: isOwnMessage ? 'white' : '#333',
                            padding: '12px 16px',
                            borderRadius: '18px',
                            borderTopLeftRadius: isOwnMessage ? '18px' : '4px',
                            borderTopRightRadius: isOwnMessage ? '4px' : '18px',
                            wordBreak: 'break-word',
                            lineHeight: '1.5',
                            position: 'relative',
                            maxWidth: '100%'
                          }}
                        >
                          {msg.content}
                          
                          <div
                            style={{
                              fontSize: '11px',
                              opacity: 0.7,
                              marginTop: '4px',
                              textAlign: isOwnMessage ? 'right' : 'left'
                            }}
                          >
                            {messageTime}
                        </div>
                      </div>
                        
                      {isOwnMessage && (
                        <Avatar
                            size={32}
                          src={user?.avatar}
                          icon={<UserOutlined />}
                            style={{ flexShrink: 0 }}
                        />
                      )}
                    </div>
                  </div>
                );
                })}
                <div ref={chatMessagesEndRef} />
              </div>
            ) : (
              <div className="no-messages">
                <Empty
                  description="暂无消息记录"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              </div>
            )}
          </div>

          {/* 输入区域 */}
          <div className="chat-input-area">
            <div className="input-container">
              <TextArea
                value={chatMessage}
                onChange={(e) => setChatMessage(e.target.value)}
                onKeyDown={handleChatKeyDown}
                placeholder="输入消息..."
                autoSize={{ minRows: 1, maxRows: 4 }}
                className="chat-message-input"
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={sendChatMessage}
                loading={sending}
                disabled={!chatMessage.trim()}
                className="chat-send-btn"
              />
            </div>
          </div>
        </div>
      </Modal>

      {/* 对话历史模态框 */}
      <Modal
        title="对话历史"
        open={showHistoryModal}
        onCancel={() => setShowHistoryModal(false)}
        footer={null}
        width={800}
        className="history-modal"
      >
        {historyConversation && (
          <div className="history-content">
            <div className="history-header">
              <Avatar
                size={48}
                src={chatModalUser?.avatar || historyConversation.avatar}
                icon={<UserOutlined />}
              />
              <div className="history-info">
                <Title level={4}>{historyConversation.title}</Title>
                <Text>共 {messages.length} 条消息</Text>
              </div>
            </div>
            
            <div className="history-messages">
              {messages.map(renderMessage)}
            </div>
          </div>
        )}
      </Modal>

      {/* 新会话模态框 */}
      <Modal
        title="发起新会话"
        open={showNewConversationModal}
        onCancel={() => {
          setShowNewConversationModal(false);
          setSearchContactKeyword("");
        }}
        footer={null}
        width={600}
        className="new-conversation-modal"
      >
        <div className="new-conversation-content">
          {/* 搜索框 */}
          <div className="contact-search">
            <Search
              placeholder="搜索联系人..."
              value={searchContactKeyword}
              onChange={(e) => setSearchContactKeyword(e.target.value)}
              className="contact-search-input"
            />
          </div>

          {/* 联系人列表 */}
          <div className="contacts-list">
            {frequentContacts
              .filter(contact => 
                contact.name.toLowerCase().includes(searchContactKeyword.toLowerCase()) ||
                contact.email.toLowerCase().includes(searchContactKeyword.toLowerCase())
              )
              .map((contact) => (
                <div
                  key={contact.id}
                  className="contact-item"
                  onClick={() => selectContactToChat(contact)}
                >
                  <div className="contact-avatar">
                    <Avatar
                      size={48}
                      src={contact.avatar}
                      icon={<UserOutlined />}
                    />
                    <div className={`online-indicator ${Math.random() > 0.5 ? 'online' : 'offline'}`} />
                  </div>
                  
                  <div className="contact-info">
                    <div className="contact-name">
                      <Text strong>{contact.name}</Text>
                      <Tag 
                        color={
                          contact.role === 'teacher' ? 'blue' : 
                          contact.role === 'admin' ? 'red' : 'green'
                        }
                      >
                        {contact.role === 'teacher' ? '教师' : 
                         contact.role === 'admin' ? '管理员' : '学生'}
                      </Tag>
                    </div>
                    <Text type="secondary" className="contact-email">
                      {contact.email}
                    </Text>
                  </div>
                  
                  <div className="contact-action">
                    <Button
                      type="primary"
                      size="small"
                      icon={<MessageOutlined />}
                    >
                      开始聊天
                    </Button>
                  </div>
                </div>
              ))}
          </div>

          {/* 空状态 */}
          {frequentContacts.filter(contact => 
            contact.name.toLowerCase().includes(searchContactKeyword.toLowerCase()) ||
            contact.email.toLowerCase().includes(searchContactKeyword.toLowerCase())
          ).length === 0 && (
            <div className="no-contacts">
              <Empty
                description={
                  searchContactKeyword 
                    ? `未找到包含"${searchContactKeyword}"的联系人`
                    : "暂无常用联系人"
                }
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default function MessageCenterWithBoundary(props: any) {
  return (
    <ErrorBoundary>
      <MessageCenter {...props} />
    </ErrorBoundary>
  );
}
